package com.hzit.filter;

import cn.hutool.core.util.StrUtil;
import com.hzit.properties.SecurityGatewayProperties;
import com.hzit.utils.JwtUtils;
import com.hzit.utils.ResponseUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.function.Predicate;

/**
 * 作者：李嘉浩
 * 时间：2024-08-31-10:33
 * 功能：
 */

@Configuration
@Slf4j
public class MyGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private SecurityGatewayProperties properties;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest.Builder mutate = request.mutate();

        String path = request.getURI().getPath();
        if (properties.getWhites().contains(path)){
            return chain.filter(exchange);
        }

        String authorization = request.getHeaders().getFirst("Authorization");
        if (!StrUtil.isNotBlank(authorization)){
            return ResponseUtil.webFluxResponseWriter(response,"登录失败");
        }
        String token = authorization.replace("Bearer ", "");
        Claims claims = JwtUtils.parseToken(token);
        Object uuid = claims.get("uuid");
        Boolean aBoolean = redisTemplate.hasKey("access_token" + uuid);
        if (!aBoolean){
            return ResponseUtil.webFluxResponseWriter(response,"登录失败");
        }


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
